<template>
	<view class="mainview">
		<textarea class="news" v-model="userMessage" maxlength="-1" placeholder="输入新消息" auto-height @tap="focus" @focus="focus" @blur="blur" />
		<u-button class="send" size="mini" type="primary" @tap="sendMessage">发送</u-button>
	</view>
</template>

<script>
let msgType = require('../../../msgtype');

export default {
	components: {},
	props: {
		username: {
			type: Object,
			value: {}
		},
		chatType: {
			type: String,
			value: msgType.chatType.SINGLE_CHAT
		}
	},
	data() {
		return {
			inputMessage: '', // render input 的值
			userMessage: '' // input 的实时值
		};
	},
	created() {},

	onReady() {},
	methods: {
		focus() {
			this.$emit('inputFocused');
		},

		blur() {
			this.$emit('inputBlured');
		},

		isGroupChat() {
			return this.chatType == msgType.chatType.CHAT_ROOM;
		},

		getSendToParam() {
			return this.isGroupChat() ? this.username.groupId : this.username.your;
		},

		emojiAction(emoji) {
			let str;
			let msglen = this.userMessage.length - 1;
			if (emoji && emoji != '[del]') {
				str = this.userMessage + emoji;
			} else if (emoji == '[del]') {
				let start = this.userMessage.lastIndexOf('[');
				let end = this.userMessage.lastIndexOf(']');
				let len = end - start;
				if (end != -1 && end == msglen && len >= 3 && len <= 4) {
					str = this.userMessage.slice(0, start);
				} else {
					str = this.userMessage.slice(0, msglen);
				}
			}
			this.userMessage = str;
		},

		sendMessage() {
			let me = this;

			String.prototype.trim = function() {
				return this.replace(/(^\s*)|(\s*$)/g, '');
			};
			if (!this.userMessage.trim()) {
				return;
			}
			let id = this.$im.conn.getUniqueId();
			let msg = new this.$im.message(msgType.TEXT, id);
			msg.set({
				msg: this.userMessage,
				from: this.username.myName,
				to: this.getSendToParam(),
				roomType: false,
				chatType: this.chatType,
				success(id, serverMsgId) {
					console.log('成功了');
					me.$disp.fire('em.chat.sendSuccess', id, me.userMessage);
				},
				fail(id, serverMsgId) {
					console.log('失败了');
				}
			});
			if (this.chatType == msgType.chatType.CHAT_ROOM) {
				msg.setGroup('groupchat');
			}
			try {
				me.$im.conn.send(msg.body);
			} catch (e) {
				console.log(e);
			}
			
			console.log(msg)

			uni.$emit('saveSendMsg', {
				msg: msg,
				type: msgType.TEXT
			});
			this.userMessage = '';
		}
	}
};
</script>

<style>
.mainview {
	display: flex;
	align-items: center;
	padding: 10upx 20upx;
}
.news {
	width: 100%;
	font-size: 28rpx;
	line-height: 50rpx;
	padding: 10upx;
	max-height: 250upx;
}
.send {
	width: 100upx;
}
</style>
